package com.yonyou.pmclouds.basecom.lock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 在被拦截的服务类的调用结束后，自动释放被该类加锁的锁
 *
 * @see PMLock
 * @see AutoReleaseLockManageAspect
 */
public class AutoReleaseLockUtil {
    private static Logger log = LoggerFactory.getLogger(AutoReleaseLockUtil.class);

    private AutoReleaseLockUtil() {
    }

    /**
     * 添加自动释放的锁，强制自动添加timeout
     *
     * @param key 要锁的关键字
     */
    public static boolean addAutoReleaseLock(String key) {
        return addAutoReleaseLock(key, PMLock.DEFAULT_TIME_OUT);
    }

    /**
     * 添加自动释放的锁，需要timeout
     *
     * @param key     要锁的关键字
     * @param timeout 锁的超时时间
     */
    public static boolean addAutoReleaseLock(String key, long timeout) {
        try {
            boolean result = PMLock.addLock(key, timeout);
            if (result) {
                AutoReleaseLockManageAspect.addLockInfo(key);
            }
            return result;
        } catch (InterruptedException e) {
            log.error("加锁失败，key:{}", key);
            return false;
        }
    }

    /**
     * 添加自动释放的锁，需要timeout
     *
     * @param key      要锁的关键字
     * @param timeout  锁的超时时间
     * @param waitTime 获取锁要可以等待的时间
     */
    public static boolean addAutoReleaseLock(String key, long timeout, long waitTime) {
        try {
            boolean result = PMLock.addLock(key, waitTime, timeout);
            if (result) {
                AutoReleaseLockManageAspect.addLockInfo(key);
            }
            return result;
        } catch (InterruptedException e) {
            log.error("加锁失败，key:{}", key);
            return false;
        }
    }
}
